package cc.eddic.practice.spring.webapi;

import cc.eddic.practice.spring.dto.*;
import cc.eddic.practice.spring.repository.QuestionRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("api/questions")
public class QuestionRestController {


    public QuestionRestController(QuestionRepository questionRepository){this.questionRepository=questionRepository;}


    public HttpEntity<?> add(@RequestBody final QuestionAddRequest model){
        val question = questionRepository.save(model.as());
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(question.getId()).toUri()).build();
    }


    @GetMapping("/{id}")
    public HttpEntity<QuestionResponse> get(@PathVariable("id") final long id){
        if (log.isDebugEnabled()) log.debug("id = {}",id);
        val question = questionRepository.findById(id).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(QuestionResponse.from(question));
    }


    @GetMapping("/{questionId}/options")
    public HttpEntity<?> get(@PathVariable("questionId") Long questionId){
        if (log.isDebugEnabled()) log.debug("categoryId = {}",questionId);
        val question = questionRepository.findById(questionId).orElseThrow(NoSuchElementException::new);
        if (log.isDebugEnabled()) log.debug("run lazy load");
        return ResponseEntity.ok(question.getOptions().stream().map(OptionResponse::from).collect(Collectors.toList()));
    }

    @GetMapping("/{questionId}/options/{optionId}")
    public HttpEntity<?> get(@PathVariable("questionId") Long questionId,@PathVariable("optionId") Long optionId ){
        if (log.isDebugEnabled()) log.debug("questionId = {},optionId = {}",questionId,optionId);
        val category = questionRepository.findById(questionId).orElseThrow(NoSuchElementException::new);
        val option = category.getOptions().stream().filter(option1 -> option1.getId().equals(optionId)).findFirst().orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(OptionResponse.from(option));
    }



    final QuestionRepository questionRepository;
}
